﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using XWG.JWBST.ProcessInterfaces;
using XWG.JWBST.Factory;
using System.Web.SessionState;
using System.Net;
using System.Text;

namespace JWBSTManagementApp
{
    /// <summary>
    /// ModuleHandles 的摘要说明
    /// </summary>
    public class ModuleHandles : IHttpHandler, IRequiresSessionState
    {
        // 测试用方法，输出接收到信息
        private void WriteLog(Stream ss, string pn, HttpContext context)
        {
            StreamWriter sw = new StreamWriter(HttpContext.Current.Server.MapPath("") + "\\log.txt", true);
            StreamReader sr = new StreamReader(ss);
            sw.WriteLine("时间：{0} \r\n 操作：{1} \r\n 内容：{2} \r\n 格式：{3}", DateTime.Now.ToString(), pn, HttpUtility.UrlDecode(sr.ReadToEnd()), (context.Request.ContentEncoding).BodyName);
            ss.Seek(0, SeekOrigin.Begin);
            sr = null;
            sw.Close();
        }


        public void ProcessRequest(HttpContext context)
        {
            try
            {
                // 获取处理逻辑名 未提交认为是非法请求
                string pn = context.Request.QueryString["pn"];
                if (string.IsNullOrEmpty(pn))
                {
                    context.Response.ContentType = "text/plain";
                    context.Response.Write("非法请求！");
                    return;
                }

                // 记录提交数据
                WriteLog(context.Request.InputStream, pn,context);

                // 根据处理逻辑名创建处理对象
                IProcess process = ProcessFactory.CreateProcess(pn);
                StreamReader inputReader = new StreamReader(context.Request.InputStream);
                context.Response.ContentType = "text/plain";
                string responseData = process.ProcessData(inputReader, context);
                File.AppendAllText(HttpContext.Current.Server.MapPath("") + "\\log.txt", "返回值："+responseData + "\r\n"+"______________________________________\r\n");
                context.Response.Write(responseData);

            }
            catch (Exception ex)
            {
                context.Response.ContentType = "text/plain";
                context.Response.Write(ex.Message);
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}